<?php
/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2023-10-17
 * Time: 14:44:36
 * Info:
 */

namespace plugin\huiblog\app\model;

use think\Model;
use support\Cache;

class Nav extends Model
{

    protected $table = 'blog_nav';

    /**
     * 自动时间戳类型
     * @var string
     */
    protected $autoWriteTimestamp = true;

    /**
     * 添加时间
     * @var string
     */
    protected $createTime = 'create_time';

    /**
     * 更新时间
     * @var string
     */
    protected $updateTime = 'update_time';

    /**
     * 前台调用导航
     */
    public function getNavs($navName)
    {
        if (Cache::get('blogNav'.$navName)) {
            $navs = Cache::get('blogNav'.$navName);
        } else {
            $nav_id = (new NavGroup())->where(['name' => $navName, 'status' => 1])->value('id');
            if (empty($nav_id)) {
                return [];
            }
            $list = $this->where(['group_id' => $nav_id, 'status' => 1])->order('sort asc')->select()->toArray();
            $navs = list_to_tree($list);
            Cache::set('blogNav'.$navName, $navs);
        }

        return $navs;
    }

    /**
     * 默认是否显示全部
     */
    public function getPidNavList($parentId = '0')
    {
        $where       = function ($query) use ($parentId) {
            if ( ! empty($parentId)) {
                $query->where('pid', $parentId);
            }
        };
        $list        = $this->field('id,pid,title')->where($where)->select();
        $pidMenuList = $this->buildPidMenu($parentId, $list->toArray());

        return $pidMenuList;
    }

    protected function buildPidMenu($pid, $list, $level = 0)
    {
        $newList = [];
        foreach ($list as $vo) {
            if ($vo['pid'] == $pid) {
                $level++;
                foreach ($newList as $v) {
                    if ($vo['pid'] == $v['pid'] && isset($v['level'])) {
                        $level = $v['level'];
                        break;
                    }
                }
                $vo['level'] = $level;
                if ($level > 1) {
                    $repeatString = "&nbsp;&nbsp;";
                    $markString   = str_repeat("{$repeatString}├{$repeatString}", $level - 1);
                    $vo['title']  = $markString.$vo['title'];
                }
                $newList[] = $vo;
                $childList = $this->buildPidMenu($vo['id'], $list, $level);
                ! empty($childList) && $newList = array_merge($newList, $childList);
            }

        }

        return $newList;
    }

}
